package handlers

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"gorm.io/gorm"
	"hello/database"
	models "hello/models"
	"hello/utils"
	"net/http"
)

// isStorageFieldExist 检查指定字段是否已存在有效记录
func isStorageFieldExist(field, value string) (bool, error) {
	var storage models.Storage
	err := database.DB.Where(field+" = ? AND status = 1", value).First(&storage).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return false, nil
		}
		return false, err
	}
	return true, nil
}

func CreateStorage(ctx *gin.Context) {
	var updateStorageDTO models.UpdateStorageDTO

	if err := ctx.ShouldBindJSON(&updateStorageDTO); err != nil {
		ctx.JSON(http.StatusBadRequest, utils.JSONResult{
			Code:    http.StatusBadRequest,
			Message: "绑定参数失败",
			Data:    err.Error(),
		})
		return
	}

	if err := updateStorageDTO.Validate(); err != nil {
		errorsMap := make(map[string]string)
		if validationErrs, ok := err.(validator.ValidationErrors); ok {
			for _, fieldErr := range validationErrs {
				errorsMap[fieldErr.Field()] = fieldErr.Tag()
			}
		}
		ctx.JSON(http.StatusBadRequest, utils.JSONResult{
			Code:    http.StatusBadRequest,
			Message: "参数错误",
			Data:    errorsMap,
		})
		return
	}

	// 检查 name 是否重复
	exist, err := isStorageFieldExist("name", updateStorageDTO.Name)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, utils.JSONResult{
			Code:    http.StatusBadRequest,
			Message: "系统错误",
			Data:    nil,
		})
		return
	}
	if exist {
		ctx.JSON(http.StatusConflict, utils.JSONResult{
			Code:    http.StatusConflict,
			Message: fmt.Sprintf("仓库名称 '%s' 已被使用", updateStorageDTO.Name),
			Data:    nil,
		})
		return
	}

	// 检查 code 是否重复
	exist, err = isStorageFieldExist("code", updateStorageDTO.Code)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, utils.JSONResult{
			Code:    http.StatusBadRequest,
			Message: "系统错误",
			Data:    nil,
		})
		return
	}
	if exist {
		ctx.JSON(http.StatusConflict, utils.JSONResult{
			Code:    http.StatusConflict,
			Message: fmt.Sprintf("仓库编码 '%s' 已被使用", updateStorageDTO.Code),
			Data:    nil,
		})
		return
	}

	storageD := &models.Storage{
		MerchantId: updateStorageDTO.MerchantId,
		Name:       updateStorageDTO.Name,
		Code:       updateStorageDTO.Code,
		Status:     updateStorageDTO.Status,
	}

	if err := database.DB.Create(storageD).Error; err != nil {
		ctx.JSON(http.StatusInternalServerError, utils.JSONResult{
			Code:    http.StatusInternalServerError,
			Message: "保存失败",
			Data:    "系统内部错误",
		})
		return
	}

	ctx.JSON(http.StatusOK, utils.JSONResult{
		Code:    http.StatusOK,
		Message: "保存成功",
		Data:    storageD,
	})
}
